

import org.apache.log4j.Logger;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author user_xdd
 * @Date 2022-04-15 10:58
 * @description
 * @return
 */
public class image3 {
        private static  final Logger LOGGER = Logger.getLogger(image3.class);
    /**
     * 下载图片
     * @param urlString
     * @param urlName 文件路径
     * @param savePath 保存路径
     */
    public static Map<String, Object> download(String urlName , String savePath){
        Map<String, Object> res = new HashMap<String, Object>();
        String code = null;
        String msg = "下载成功：图片存放在：C://";
        // 构造URL
        InputStream is = null;
        OutputStream os = null;
        try {
            URL url = new URL(urlName);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            os = new FileOutputStream(savePath);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            code = "999";
            msg = "下载失败";
        } finally {
            try {
                // 完毕，关闭所有链接
                if (null != is && null != os) {
                    is.close();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        res.put("code", code);
        res.put("msg", msg);
        return res;
    }

    public static void main(String[] args) {
        Map<String, Object> download = download("https://www.linovelib.com/files/article/image/3/3166/3166s.jpg", "D:\\my_tool\\OneDrive - xdd307\\弘成\\6.javaWeb\\xdd\\项目设计\\bookManager2.1\\src\\main\\webapp\\data");
         LOGGER.debug("    download:"+download);
    }
}
